package com.osmino.contacts.provider;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;

public final class CallLogQueries {

	private static final Uri CALLS_CONTENT_URI = CallLog.Calls.CONTENT_URI;
	private static final String[] CALLS_PROJECTION = new String[] {//
	/*    */CallLog.Calls._ID,//
			CallLog.Calls.CACHED_NAME, //
			CallLog.Calls.TYPE,//
			CallLog.Calls.NUMBER, //
			CallLog.Calls.CACHED_NUMBER_TYPE, //
			CallLog.Calls.CACHED_NUMBER_LABEL, //
			CallLog.Calls.DATE, //
			CallLog.Calls.DURATION //
	};
	private static final String CALLS_SORT_ORDER = CallLog.Calls.DEFAULT_SORT_ORDER;

	private static final Cursor getRawCalls(Context context, String selection) {
		final Uri uri = CALLS_CONTENT_URI;
		final String[] projection = CALLS_PROJECTION;
		final String sortOrder = CALLS_SORT_ORDER;
		return context.getContentResolver().query(uri, projection, selection, null, sortOrder);
	}

	public static final Cursor getAllCalls(Context context) {
		return getRawCalls(context, null);
	}

	public static final Cursor getIncomingCalls(Context context) {
		final StringBuilder selectionBuilder = new StringBuilder(CallLog.Calls.TYPE);
		selectionBuilder.append(" = ").append(CallLog.Calls.INCOMING_TYPE);
		return getRawCalls(context, selectionBuilder.toString());
	}

	public static final Cursor getOutgoingCalls(Context context) {
		final StringBuilder selectionBuilder = new StringBuilder(CallLog.Calls.TYPE);
		selectionBuilder.append(" = ").append(CallLog.Calls.OUTGOING_TYPE);
		return getRawCalls(context, selectionBuilder.toString());
	}

	public static final Cursor getMissedCalls(Context context) {
		final StringBuilder selectionBuilder = new StringBuilder(CallLog.Calls.TYPE);
		selectionBuilder.append(" = ").append(CallLog.Calls.MISSED_TYPE);
		return getRawCalls(context, selectionBuilder.toString());
	}

	public static final int deleteCallHistory(Context context) {
		final Uri uri = CALLS_CONTENT_URI;
		return context.getContentResolver().delete(uri, null, null);
	}
	
	public static final int deleteCall(Context context, long id) {
		final Uri uri = CALLS_CONTENT_URI;
		final StringBuilder selectionBuilder = new StringBuilder();
		selectionBuilder.append(CallLog.Calls._ID);
		selectionBuilder.append(" = ").append(id);
		return context.getContentResolver().delete(uri, selectionBuilder.toString(), null);
	}
}
